package com.springcloud.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @Author: wukc
 * @Description: TODO
 * @DateTime: 2022/1/5 14:20
 **/
@RestController
public class DownloadController {

    //下载文件路径
    @Value("${fileUpload.info}")
    private String path;

    /**
     * 下载文件接口，可用于pdf预览
     * @param uuid  文件唯一id
     * @param resp
     * @throws Exception
     */
    @RequestMapping("/download.do")
    public void downloadFile(String uuid, HttpServletResponse resp) throws Exception {
        System.err.println(uuid);
        if(uuid==null||uuid==""){
            return;
        }
        File f = new File(path);
        if (!f.exists()) {
            throw new FileNotFoundException("file not exists");
        }
        DataInputStream in = null;
        OutputStream out = null;
        resp.setCharacterEncoding("UTF-8");
        //根据uuid获取文件名
        String filename = "";
        String filepath = "";
        if (!f.exists()) {
            System.out.println(filepath + " not exists");
            return;
        }
        File fa[] = f.listFiles();
        for (int i = 0; i < fa.length; i++) {
            File fs = fa[i];
            if (!fs.isDirectory()) {
                String filename1 = fs.getName();
                if(filename1.indexOf(uuid)!=-1){
                    filename = filename1.replace((uuid+"-"),"");
                    filepath = fs.getPath();
                    break;
                }
            }
        }
        if(filename== ""){
            throw new Exception("文件不存在，或已损坏");
        }
        resp.setHeader("Content-disposition", "attachment; filename=" + new String(filename.getBytes("utf-8"),"ISO8859-1"));// 设定输出文件头
        Path path = Paths.get(filepath);
        String contentType = Files.probeContentType(path);
        resp.setHeader(HttpHeaders.CONTENT_TYPE, contentType);

        //输入流：本地文件路径
        in = new DataInputStream(new FileInputStream(new File(filepath)));
        //输出流
        out = resp.getOutputStream();
        //输出文件
        int bytes = 0;
        byte[] bufferOut = new byte[1024];
        while ((bytes = in.read(bufferOut)) != -1) {
            out.write(bufferOut, 0, bytes);
        }
        try {
            OutputStreamWriter writer = new OutputStreamWriter(resp.getOutputStream(), StandardCharsets.UTF_8);
            writer.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        if (null != in) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (null != out) {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
